﻿using System;
using System.Collections.Concurrent;
using System.Net.Http;
using System.Threading.Tasks;
namespace ExcelCOMAddin
{
    public static class HttpClientPool
    {
        private static readonly ConcurrentBag<HttpClient> _clients = new();
        private static readonly object _lock = new();
        private static int _maxClients = Environment.ProcessorCount * 2;
        private static int _currentClients = 0;

        public static HttpClient GetClient()
        {
            if (_clients.TryTake(out HttpClient client))
            {
                return client;
            }

            lock (_lock)
            {
                if (_currentClients < _maxClients)
                {
                    _currentClients++;
                    return CreateNewClient();
                }
            }

            Task.Delay(10).Wait();
            return GetClient();
        }

        public static void ReturnClient(HttpClient client)
        {
            if (_clients.Count < _maxClients && _currentClients <= _maxClients)
            {
                _clients.Add(client);
            }
            // 否则丢弃
        }

        private static HttpClient CreateNewClient()
        {
            var handler = new HttpClientHandler
            {
                AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate
            };

            var client = new HttpClient(handler)
            {
                Timeout = TimeSpan.FromSeconds(30),
                MaxResponseContentBufferSize = 1024 * 1024 * 10 // 10MB
            };

            client.DefaultRequestHeaders.UserAgent.ParseAdd("EastMoneyRTD/1.0");
            client.DefaultRequestHeaders.ConnectionClose = false;

            return client;
        }
    }
}